<?php
/**
 * Created by PhpStorm.
 * User: Yangjinlei
 * Date: 2018/7/6
 * Time: 9:38
 */

namespace app\traits;


use think\Response;

trait ApiResponse
{

    /**
     * @var array 调试信息
     */
    private $debugInfo = [];

    protected $headers = [];

    public function response($code,$msg,$data='',$headers=[])
    {
        $this->setHeaders($headers);
        $responseData = ['code'=>$code,'msg'=>$msg];
        if (!empty($data))
            $responseData['data'] = $data;
        if (!empty($this->debugInfo))
            $responseData['info'] = $this->debugInfo;
//        $this->appLog($responseData);
        return Response::create($responseData, 'json', 200, $this->headers);
    }

    /**
     * @param array $headers 添加特殊的头信息
     */
    public function setHeaders($headers=[]){
        if (!empty($headers))
            $this->headers = array_merge($this->headers,$headers);
    }

    public function success($data,$msg='success',$code=200){
        return $this->response($code,$msg,$data);
    }

    /**
     * @param mixed $info 调试信息
     */
    final public function debug($info){
        array_push($this->debugInfo,$info);
    }

    public function error($code,$msg='error'){
        return $this->response($code,$msg);
    }
}